package com.cs.pk;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Properties;

import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;

import com.cs.pk.utils.Constants;
import com.cs.pk.utils.CustomList;
import com.cs.pk.utils.Util;

/**
 * The activator class controls the plug-in life cycle
 */
public class Activator extends AbstractUIPlugin {

    // The plug-in ID
    public static final String PLUGIN_ID = "com.pk.nds";

    // The shared instance
    private static Activator plugin;

    private Bundle pluginBundle = null;

    private Properties defaultPreference = null;

    public String clearcase_file_path = null;

    public CustomList localBuildItems = new CustomList("local");

    public CustomList remoteBuildItems = new CustomList("remote");

    /**
     * The constructor
     */
    public Activator() {
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext
     * )
     */
    public void start(BundleContext context) throws Exception {
	super.start(context);
	File codeStriker = new File(System.getProperty("user.dir"), PLUGIN_ID);
	if (!codeStriker.exists()) {
	    codeStriker.mkdir();
	}
	pluginBundle = context.getBundle();
	plugin = this;
	initDefaultPreferencesOfPlugin(getPreferenceStore());
	createBuildList();
    }

    private void createBuildList() {
	String value = Util.getValues(Constants.BUILD_ITEM_KEY);
	if (value != null && !value.trim().equals("")) {
	    String tokens[] = value.split(":");
	    for (int i = 0; i < tokens.length; i++) {
		localBuildItems.add(tokens[i]);
	    }
	}
	value = Util.getValues(Constants.REMOTE_BUILD_ITEM_KEY);
	if (value != null && !value.trim().equals("")) {
	    String tokens[] = value.split(":");
	    for (int i = 0; i < tokens.length; i++) {
		remoteBuildItems.add(tokens[i]);
	    }
	}
    }

    public void saveBuildItems() {
	String value = "";
	Iterator iterator = localBuildItems.iterator();
	if (iterator.hasNext()) {

	    for (;;) {
		value += (String) iterator.next();
		if (!iterator.hasNext()) {
		    break;
		}
		value += ":";
	    }
	}
	if (!"".equals(value)) {
	    Util.setValue(Constants.BUILD_ITEM_KEY, value);
	}
	value = "";
	iterator = remoteBuildItems.iterator();
	if (iterator.hasNext()) {
	    for (;;) {
		value += (String) iterator.next();
		if (!iterator.hasNext()) {
		    break;
		}
		value += ":";
	    }
	}
	if (!"".equals(value)) {
	    Util.setValue(Constants.REMOTE_BUILD_ITEM_KEY, value);
	}
    }

    public boolean appendToLocalBuiltItem(String value) {
	if (!localBuildItems.contains(value)) {
	    return localBuildItems.add(value);
	}
	return false;
    }

    public boolean appendToRemoteBuiltItem(String value) {
	if (!remoteBuildItems.contains(value)) {
	    return remoteBuildItems.add(value);
	}
	return false;
    }

    public void removeLocalBuildItem(String value) {
	localBuildItems.remove(value);
    }

    public void removeRemoteBuildItem(String value) {
	remoteBuildItems.remove(value);
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext
     * )
     */
    public void stop(BundleContext context) throws Exception {
	plugin = null;
	super.stop(context);
    }

    /**
     * Returns the shared instance
     * 
     * @return the shared instance
     */
    public static Activator getDefault() {
	return plugin;
    }

    /**
     * Returns an image descriptor for the image file at the given plug-in
     * relative path
     * 
     * @param path
     *            the path
     * @return the image descriptor
     */
    public static ImageDescriptor getImageDescriptor(String path) {
	return imageDescriptorFromPlugin(PLUGIN_ID, path);
    }

    private void initDefaultPreferencesOfPlugin(IPreferenceStore store) {
	try {
	    defaultPreference = new Properties();
	    InputStream is = pluginBundle.getEntry("/default.properties")
		    .openStream();
	    defaultPreference.load(is);
	    is.close();
	    readDefaultCommands();
	    saveClearCaseCommands();
	} catch (IOException e) {
	    e.printStackTrace();
	}
    }

    private void readDefaultCommands() throws IOException {
	InputStream is = pluginBundle.getEntry("/buildcommands.properties")
		.openStream();
	StringBuffer sb = new StringBuffer();
	byte b[] = new byte[512];
	int n = 0;
	while ((n = is.read(b)) > -1) {
	    sb.append(new String(b, 0, n));
	    b = new byte[512];
	}
	is.close();
	defaultPreference.put(Constants.CYGWIN_CMD, sb.toString());
    }

    public void saveClearCaseCommands() throws IOException {
	File clearcase = new File(Platform.getConfigurationLocation().getURL()
		.getFile(), Constants.CLEARCASE_FILE);
	clearcase_file_path = clearcase.getAbsolutePath();
	if (!clearcase.getParentFile().exists()) {
	    clearcase.getParentFile().mkdirs();
	}

	if (!clearcase.exists()
		|| pluginBundle.getLastModified() > clearcase.lastModified()) {
	    clearcase.createNewFile();

	    InputStream is = pluginBundle.getEntry("/clearcase.properties")
		    .openStream();
	    StringBuffer sb = new StringBuffer();
	    byte b[] = new byte[512];
	    int n = 0;
	    while ((n = is.read(b)) > -1) {
		sb.append(new String(b, 0, n));
		b = new byte[512];
	    }
	    is.close();
	    FileOutputStream fos = new FileOutputStream(clearcase);
	    fos.write(sb.toString().getBytes());
	    fos.flush();
	    fos.close();
	}
    }

    public String getDefaultPreference(String key) {
	return defaultPreference.getProperty(key);
    }

}
